package com.lvxh.exp.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Locale;

import com.lvxh.exp.bean.TableProperties;

public class XmlUtil
{
    public static void initMybatisXml(String fileAboPath,  String tableName, String filePackage,List<TableProperties> plist)
    {
        String className = StringUtil.headToUpperCase(tableName);
        filePackage = filePackage+"." + tableName;
        File dir = new File(fileAboPath+"/"+tableName + "/dao/mapper/");
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(fileAboPath+"/"+tableName +  "/dao/mapper/"+StringUtil.headToUpperCase(tableName)+"Mapper.xml");
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try
        {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
            osw.write(System.getProperty("line.separator"));

            osw.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >");
            osw.write(System.getProperty("line.separator"));

            osw.write("<mapper namespace=\"" + filePackage + ".dao" + "."
                    + className + "Mapper\" >");
            osw.write(System.getProperty("line.separator"));

            osw.write("<resultMap id=\"BaseResultMap\" type=\"" + filePackage
                    + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            StringBuffer buf = new StringBuffer();
            StringBuffer buf1 = new StringBuffer();
            StringBuffer buf2 = new StringBuffer();
            StringBuffer buf3 = new StringBuffer();
            TableProperties pri = null;
            for (int i = 0; i < plist.size(); i++)
            {

                if ("pri".equals(plist.get(i).getKey()
                        .toLowerCase(Locale.getDefault())))
                {
                    pri = plist.get(i);
                }
                else
                {

                    buf3.append(plist.get(i).getField() + "=#{"
                            + plist.get(i).getField() + "}");
                    if (i < plist.size() - 1)
                    {
                        buf3.append(",");

                    }
                }
                osw.write(" <result column=\"" + plist.get(i).getField()
                        + "\" property=\"" + plist.get(i).getField() + "\"/>");
                osw.write(System.getProperty("line.separator"));
                osw.flush();
                buf.append(plist.get(i).getField());
                buf2.append("#{" + plist.get(i).getField() + "}");
                if (i < plist.size() - 1)
                {
                    buf.append(",");
                    buf2.append(",");

                }

                buf1.append(" <if test=\"" + plist.get(i).getField()
                        + " != null ");
                if ("String".equals(BeanUtil.dbTypeToJavaType(plist.get(i)
                        .getType())))
                {
                    buf1.append("and " + plist.get(i).getField() + " != ''");
                }
                buf1.append("\">");
                buf1.append(System.getProperty("line.separator"));
                buf1.append("  and " + plist.get(i).getField() + " =  #{"
                        + plist.get(i).getField() + "}");
                buf1.append(System.getProperty("line.separator"));
                buf1.append("</if>");
                buf1.append(System.getProperty("line.separator"));

            }

            osw.write("</resultMap>");
            osw.write(System.getProperty("line.separator"));

            /**
             * <sql id="Base_Column_List" > seqname, currentvalue, increment
             * </sql>
             */
            osw.write("<sql id=\"Base_Column_List\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  " + buf.toString());
            osw.write(System.getProperty("line.separator"));
            osw.write(" </sql>");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <sql id="Where_Clause"> where 1=1 <trim suffixOverrides="," > <if
             * test="seqname != null and seqname != ''" > and seqname =
             * #{seqname} </if> <if test="currentvalue != null" > and
             * currentvalue = #{currentvalue} </if> <if test="increment != null"
             * > and increment = #{increment} </if>
             * 
             * </trim> </sql>
             */
            osw.write(" <sql id=\"Where_Clause\">");
            osw.write(System.getProperty("line.separator"));
            osw.write("  where 1=1");
            osw.write(System.getProperty("line.separator"));
            osw.write(" <trim  suffixOverrides=\",\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write(buf1.toString());
            osw.write(" </trim>");
            osw.write(System.getProperty("line.separator"));
            osw.write(" </sql>");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <insert id="insert"
             * parameterType="com.lvxh.exp.dao.holder.Sequence" > insert into
             * sequence (seqname, currentvalue, increment ) values
             * (#{seqname,jdbcType=VARCHAR}, #{currentvalue,jdbcType=INTEGER},
             * #{increment,jdbcType=INTEGER} ) </insert>
             */
            osw.write("<insert id=\"insert\" parameterType=\"" + filePackage
                    + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  insert into " + className.toLowerCase() + " ("
                    + buf.toString() + ")values (" + buf2.toString() + ")");
            osw.write(System.getProperty("line.separator"));
            osw.write("</insert>");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <!-- 根据主键，修改记录--> <update id="update"
             * parameterType="com.cloudycd.tcs.holder.ActivityDialogHolder" >
             * update ActivityDialog set
             * Name=#{name},ActivityId=#{activityId},employeeId=#{employeeId},
             * PeopleName
             * =#{peopleName},Content=#{content},CreateTime=#{createTime
             * },CreBy=#{creBy},
             * CreDate=#{creDate},UpdBy=#{updBy},UpdDate=#{updDate
             * },IsDel=#{isDel} where Id=#{id} </update>
             */
            if (pri != null)
            {
                osw.write("<update id=\"update\" parameterType=\""
                        + filePackage + ".dao" + ".holder." + className
                        + "\" >");
                osw.write(System.getProperty("line.separator"));
                osw.write("  update " + className.toLowerCase() + " set ");
                osw.write(buf3.toString() + " where " + pri.getField() + "=#{"
                        + pri.getField() + "}");
                osw.write(System.getProperty("line.separator"));
                osw.write("</update>");
                osw.write(System.getProperty("line.separator"));
                osw.flush();
            }

            /**
             * <!-- 物理删除 --> <update id="delete"
             * parameterType="com.cloudycd.tcs.holder.ActivityDialogHolder">
             * delete from ActivityDialog where Id = #{id} </update>
             */
            osw.write("<delete id=\"delete\" parameterType=\"" + filePackage
                    + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  delete from " + className.toLowerCase());
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Where_Clause\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write("</delete>");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <select id="getList" resultMap="BaseResultMap"
             * parameterType="com.cloudycd.tcs.holder.ActivityDialogHolder">
             * select <include refid="Base_Column_List"/> from ActivityDialog
             * <include refid="Where_Clause"/> </select>
             */
            osw.write("<select id=\"getList\" resultMap=\"BaseResultMap\"  parameterType=\""
                    + filePackage + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  select  ");
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Base_Column_List\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write("  from " + className.toLowerCase());
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Where_Clause\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write("</select>  ");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <select id="getCountOfSummary" resultType="int"
             * parameterType="com.lvxh.exp.dao.holder.Sequence"> select count(0)
             * from sequence <include refid="Where_Clause"/> </select>
             */

            osw.write("<select id=\"getCountOfSummary\" resultType=\"int\"  parameterType=\""
                    + filePackage + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  select  count(1) from " + className.toLowerCase());
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Where_Clause\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write("</select>  ");
            osw.write(System.getProperty("line.separator"));
            osw.flush();
            /**
             * <select id="getListOfSummary" resultMap="BaseResultMap"
             * parameterType="com.lvxh.exp.dao.holder.Sequence"> select <include
             * refid="Base_Column_List"/> from sequence <include
             * refid="Where_Clause"/> <if
             * test="sortField != null and sortField != ''" > order by
             * ${sortField} ${sortOrder} </if> limit
             * ${startRecordNum},${perNumber}
             * 
             * </select>
             */
            osw.write("<select id=\"getListOfSummary\" resultMap=\"BaseResultMap\"  parameterType=\""
                    + filePackage + ".dao" + ".holder." + className + "\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  select  ");
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Base_Column_List\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write("  from " + className.toLowerCase());
            osw.write(System.getProperty("line.separator"));
            osw.write(" <include refid=\"Where_Clause\"/>");
            osw.write(System.getProperty("line.separator"));
            osw.write(" <if test=\"sortField != null and sortField != ''\" >");
            osw.write(System.getProperty("line.separator"));
            osw.write("  order by ${sortField} ${sortOrder}");
            osw.write(System.getProperty("line.separator"));
            osw.write(" </if>");
            osw.write(System.getProperty("line.separator"));
            osw.write("  limit ${startRecordNum},${perNumber}");
            osw.write(System.getProperty("line.separator"));
            osw.write("</select>  ");
            osw.write(System.getProperty("line.separator"));

            osw.write("</mapper>  ");
            osw.flush();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            ExpUtils.closeStream(osw);
            ExpUtils.closeStream(fos);

        }

    }

    public static void initMybatisConfig(String filePath, List<String> list,
            String filePackage)
    {

        File dir = new File(filePath);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(filePath + "temp.xml");
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try
        {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");

            for (String tableName : list)
            {
                /**
                 * <bean id="expUserMapper"
                 * class="org.mybatis.spring.mapper.MapperFactoryBean">
                 * <property name="mapperInterface"
                 * value="com.lvxh.exp.dao.ExpUserMapper"/> <property
                 * name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
                 */
                String pack = filePackage + "." + tableName + ".dao."
                        + StringUtil.headToUpperCase(tableName) + "Mapper";
                osw.write("<bean id=\""
                        + tableName
                        + "Mapper\" class=\"org.mybatis.spring.mapper.MapperFactoryBean\"> ");
                osw.write(System.getProperty("line.separator"));
                osw.write("  <property name=\"mapperInterface\" value=\""
                        + pack + "\"/>");
                osw.write(System.getProperty("line.separator"));
                osw.write("  <property name=\"sqlSessionFactory\" ref=\"sqlSessionFactory\"/>");
                osw.write(System.getProperty("line.separator"));
                osw.write("</bean>");
                osw.write(System.getProperty("line.separator"));
                osw.flush();

            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            ExpUtils.closeStream(osw);
            ExpUtils.closeStream(fos);

        }

    }

    public static void initQueryJsp(String jspPath, String tableName,
            List<TableProperties> list)
    {

        File dir = new File(jspPath + tableName);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(jspPath + tableName + "/view" + StringUtil.headToUpperCase(tableName) + ".jsp");
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try
        {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");
            String script=StringUtil.getQueryScript(tableName);
            String condition = StringUtil.getQueryCondition(list);
            String thead = StringUtil.getQueryThead(list);
            String template = StringUtil.getQueryTemplate(list);
            String body=StringUtil.getQueryBody(condition, thead, template);
            
            osw.write(StringUtil.getFram(script, body));

            osw.flush();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            ExpUtils.closeStream(osw);
            ExpUtils.closeStream(fos);

        }

    }
    public static void initAddJsp(String jspPath, String tableName,
            List<TableProperties> list)
    {

        File dir = new File(jspPath + tableName);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(jspPath + tableName + "/add" + StringUtil.headToUpperCase(tableName) + ".jsp");
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try
        {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");
            String script=StringUtil.getAddScript(tableName);
            String content = StringUtil.getAddContent(list);
            String body=StringUtil.getAddBody(content);
            
            osw.write(StringUtil.getFram(script, body));

            osw.flush();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            ExpUtils.closeStream(osw);
            ExpUtils.closeStream(fos);

        }

    }
    public static void initModifyJsp(String jspPath, String tableName,
            List<TableProperties> list)
    {

        File dir = new File(jspPath + tableName);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        File file = new File(jspPath + tableName + "/modify" + StringUtil.headToUpperCase(tableName) + ".jsp");
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try
        {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "UTF-8");
            String script=StringUtil.getModifyScript(tableName);
            String content = StringUtil.getModifyContent(list);
            String body=StringUtil.getModifyBody(content);
            
            osw.write(StringUtil.getFram(script, body));

            osw.flush();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            ExpUtils.closeStream(osw);
            ExpUtils.closeStream(fos);

        }

    }
}
